package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();

        Page<Object> page = PageHelper.startPage(currentPage, pageSize);

        List<Role> roles = roleDao.findByCondition(queryString);

        long total = page.getTotal();
        return new PageResult(total, roles);
    }

    @Override
    public void add(Role role) {
        roleDao.add(role);
    }

    @Override
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public void edit(Role role) {
        roleDao.edit(role);
    }

    /*删除表关系：之后再删除 role*/
    @Override
    public void delete(Integer id) {
        roleDao.deleteMenuIdsAndRoleId(id);
        roleDao.deletePermissionIdsAndRoleId(id);
        roleDao.delete(id);
    }

    @Override
    public List<Integer> findPermissionsByRoleId(Integer roleId) {
        return roleDao.findPermissionsByRoleId(roleId);
    }

    /*删除表关系之后再创建表关系*/
    @Override
    public void setPermissionsAndRoleId(Integer[] permissionIds, Integer roleId) {
        roleDao.deletePermissionIdsAndRoleId(roleId);
        if (permissionIds != null && permissionIds.length > 0) {
            for (Integer permissionId : permissionIds) {
                roleDao.setPermissionsAndRoleId(permissionId, roleId);
            }
        }
    }

    @Override
    public void setMenusAndRoleId(Integer[] menuIds, Integer roleId) {
        System.out.println("Arrays.toString(menuIds) = " + Arrays.toString(menuIds));
        System.out.println("roleId = " + roleId);
        /*先解除中间表关系，再设置关系*/
        roleDao.deleteMenuIdsAndRoleId(roleId);
        if (menuIds != null && menuIds.length > 0) {
            for (Integer menuId : menuIds) {
                roleDao.setMenuIdAndRoleId(menuId, roleId);
            }
        }
    }

}
